package com.cn.netty.customize;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

/**
 * 序列化工具
 */
@Slf4j
public class Codec {

  //序列化
  public static byte[] encode(Object obj) {
    //TODO 可以优化，对象直接转成字节
    GsonBuilder builder = new GsonBuilder();
    Gson gson = builder.create();
    String s = gson.toJson(obj);
    log.debug(s);
    byte[] bytes = s.getBytes(StandardCharsets.UTF_8);
    return bytes;
  }

  //反序列化
  public static Object decode(byte[] src) {
    //TODO
    String json = new String(src, StandardCharsets.UTF_8);
    return getBusinessMeassage(json);
  }

  public static BusinessMeassage getBusinessMeassage(String json) {
    log.debug(json);
    GsonBuilder builder = new GsonBuilder();
    Gson gson = builder.create();
    BusinessMeassage businessMeassage = gson.fromJson(json, BusinessMeassage.class);
    return businessMeassage;
  }

}
